<?php

//就近 www.jiujin.me
if (!defined('IN_IA')) {
	die('Access Denied');
}
class Ewei_DShop_Order
{
	function getDispatchPrice($weight, $d)
	{
		if (empty($d)) {
			return 0;
		}
		$price = 0;
		if ($weight <= $d['firstweight']) {
			$price = intval($d['firstprice']);
		} else {
			$price = intval($d['firstprice']);
			$secondweight = $weight - intval($d['firstweight']);
			$dsecondweight = intval($d['secondweight']) <= 0 ? 1 : intval($d['secondweight']);
			$secondprice = 0;
			if ($secondweight % $dsecondweight == 0) {
				$secondprice = $secondweight / $dsecondweight * intval($d['secondprice']);
			} else {
				$secondprice = ((int) ($secondweight / $dsecondweight) + 1) * intval($d['secondprice']);
			}
			$price += $secondprice;
		}
		return $price;
	}
	public function payResult($params)
	{
		global $_W;
                if($params['apply']==1){
                                $fee = intval($params['fee']);
                                $data = array('status' => $params['result'] == 'success' ? 1 : 0);
                                $ordersn = $params['tid'];
                                $order = pdo_fetch('select * from ' . tablename('ewei_shop_commission_apply_order') . ' where  ordersn=:ordersn and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':ordersn' => $ordersn));
                                $orderid = $order['id'];
                                if ($params['from'] == 'return') {
                                        if ($params['type'] == 'cash') {
                                                show_json(2, array('order' => $order, 'address' => "", 'carrier' =>""));
                                        } else {
                                                if ($order['status'] == 0) {
                                                        pdo_update('ewei_shop_commission_apply_order', array('status' => 1, 'paytime' => time()), array('id' => $orderid));
                                                if($order['type']==1){
                                                $order_type="银冠店980元";   
                                               }
                                               if($order['type']==2){
                                                 $order_type="金冠店2980元";   
                                               }
                                               $info=pdo_fetch('select * from '.tablename('ewei_shop_member')." where uniacid=:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$order['openid']));
                                               $msg = array(
                                                  'first' => array('value' => "申请云店通知！", "color" => "#4a5077"),
                                                   'orderName' => array('title' => '订单编号', 'value' => $order['ordersn'], "color" => "#4a5077"),
                                                   'username' => array('title' => '申请人', 'value' => $info['nickname'], "color" => "#4a5077"), 
                                                  'orderProductPrice' => array('title' => '支付金额', 'value' => '￥' . $params['fee'] . '元', "color" => "#4a5077"),
                                                  'orderProductName' => array('title' => '店铺类型', 'value' => $order_type, "color" => "#4a5077"), 
                                                  'paytime' => array('title' => '支付时间', 'value' => date('Y-m-d H:i:s',time()), "color" => "#4a5077"),
                                                   'remark' => array('value' => "\r\n请到分销中心尽快处理", "color" => "#4a5077")
                                               );
                                               m('message')->sendCustomNotice("oHpwUs5SjHizKuoPhsipTDA50ZYU", $msg);
                                                }
                                                show_json(1, array('order' => $order, 'address' =>"", 'carrier' =>""));
                                        }
                                } 
                }elseif($params['apply']==2){
                                $fee = intval($params['fee']);
                                $data = array('status' => $params['result'] == 'success' ? 1 : 0);
                                $ordersn = $params['tid'];
                                $order = pdo_fetch('select * from ' . tablename('ewei_shop_commission_experience_record') . ' where  ordersn=:ordersn and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':ordersn' => $ordersn));
                                $orderid = $order['id'];
                                if ($params['from'] == 'return') {
                                        if ($params['type'] == 'cash') {
                                                show_json(2, array('order' => $order, 'address' => "", 'carrier' =>""));
                                        } else {
                                               if ($order['status'] == 0) {
                                               pdo_update('ewei_shop_commission_experience_record', array('status' => 1, 'paytime' => time()), array('id' => $orderid));
                                               $info=pdo_fetch('select * from '.tablename('ewei_shop_member')." where uniacid=:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$order['openid']));
                                               $experience=pdo_fetch('select * from '.tablename('ewei_shop_commission_experience')." where uniacid=:uniacid and id=:id ",array(':uniacid'=>$_W['uniacid'],':id'=>$order['experienceid']));
                                               $msg = array(
                                                  'first' => array('value' => "体验券领取成功通知！", "color" => "#4a5077"),
                                                   'orderName' => array('title' => '体验客户', 'value' => $info['nickname'], "color" => "#4a5077"),
                                                   'username' => array('title' => '体验项目', 'value' => $experience['title'], "color" => "#4a5077"), 
                                                  'orderProductPrice' => array('title' => '支付金额', 'value' => '￥' . $experience['cash'] . '元', "color" => "#4a5077"),
                                                  'paytime' => array('title' => '支付时间', 'value' => date('Y-m-d H:i:s',time()), "color" => "#4a5077"),
                                                  'remark' => array('value' => "\r\n可在分销中心查看领取详情~", "color" => "#4a5077")
                                               );
                                               m('message')->sendCustomNotice($experience['openid'], $msg);
                                               }
                                              show_json(1, array('order' => $order, 'address' =>"", 'carrier' =>""));
                                        }
                                }
             }elseif($params['apply']==3){
                                $fee = intval($params['fee']);
                                $data = array('status' => $params['result'] == 'success' ? 1 : 0);
                                $ordersn = $params['tid'];
                                $order = pdo_fetch('select * from ' . tablename('franchise_apply_order') . ' where  ordersn=:ordersn and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':ordersn' => $ordersn));
                                $orderid = $order['id'];
                                if ($params['from'] == 'return') {
                                        if ($params['type'] == 'cash') {
                                                show_json(2, array('order' => $order, 'address' => "", 'carrier' =>""));
                                        } else {
                                                if ($order['status'] == 0) {
                                                pdo_update('franchise_apply_order', array('status' => 1, 'paytime' => time()), array('id' => $orderid));
                                                if($order['shop_type']==1){
                                                  $shop_type="美龄妈咪产后修复店中店";  
                                                }
                                                if($order['shop_type']==2){
                                                  $shop_type="美龄范社区母婴店";  
                                                }
                                                if($order['shop_type']==3){
                                                  $shop_type="AK系列产品";  
                                                }
                                                if($order['shop_type']==4){
                                                  $shop_type="荷尔蒙系列";  
                                                }
                                                if($order['type']==1){
                                                $order_type="方案一";   
                                               }
                                               if($order['type']==2){
                                                 $order_type="方案二";   
                                               }
                                               $info=pdo_fetch('select * from '.tablename('ewei_shop_member')." where uniacid=:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$order['openid']));
                                               $msg = array(
                                                  'first' => array('value' => "申请加盟通知！", "color" => "#4a5077"),
                                                   'orderName' => array('title' => '订单编号', 'value' => $order['ordersn'], "color" => "#4a5077"),
                                                   'username' => array('title' => '申请人', 'value' => $info['nickname'], "color" => "#4a5077"), 
                                                  'orderProductPrice' => array('title' => '支付金额', 'value' => '￥' . $params['fee'] . '元', "color" => "#4a5077"),
                                                 'orderProductShopName' => array('title' => '店铺类型', 'value' => $shop_type, "color" => "#4a5077"), 
                                                  'orderProductName' => array('title' => '加盟方案', 'value' => $order_type, "color" => "#4a5077"), 
                                                  'paytime' => array('title' => '支付时间', 'value' => date('Y-m-d H:i:s',time()), "color" => "#4a5077"),
                                                   'remark' => array('value' => "\r\n请到加盟中心尽快处理", "color" => "#4a5077")
                                               );
                                               m('message')->sendCustomNotice("oHpwUs5SjHizKuoPhsipTDA50ZYU", $msg);
                                                }
                                                show_json(1, array('order' => $order, 'address' =>"", 'carrier' =>""));
                                        }
                                }
             }else{
                                $fee = intval($params['fee']);
                                $data = array('status' => $params['result'] == 'success' ? 1 : 0);
                                $ordersn = $params['tid'];
                                $order = pdo_fetch('select id,ordersn, price,openid,dispatchtype,addressid,carrier,status,isverify,deductcredit2,gift_card from ' . tablename('ewei_shop_order') . ' where  ordersn=:ordersn and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':ordersn' => $ordersn));
                                $orderid = $order['id'];
                                if ($params['from'] == 'return') {
                                        $address = false;
                                        if (empty($order['dispatchtype'])) {
                                                $address = pdo_fetch('select realname,mobile,address from ' . tablename('ewei_shop_member_address') . ' where id=:id limit 1', array(':id' => $order['addressid']));
                                        }
                                        $carrier = false;
                                        if ($order['dispatchtype'] == 1) {
                                                $carrier = unserialize($order['carrier']);
                                        }
                                        if ($params['type'] == 'cash') {
                                                show_json(2, array('order' => $order, 'address' => $address, 'carrier' => $carrier));
                                        } else {
                                                if ($order['status'] == 0) {
                                                        pdo_update('ewei_shop_order', array('status' => 1, 'paytime' => time()), array('id' => $orderid));
                                                        if ($order['deductcredit2'] > 0) {
                                                                $shopset = m('common')->getSysset('shop');
                                                                m('member')->setCredit($order['openid'], 'credit2', -$order['deductcredit2'], array(0, $shopset['name'] . "余额抵扣: {$order['deductcredit2']} 订单号: " . $order['ordersn']));
                                                                //插入余额抵扣记录
                                                                $logno = m('common')->createNO('member_log', 'logno', 'RC');
                                                                $data = array('openid' =>$order['openid'], 'logno' => $logno, 'uniacid' => $_W['uniacid'], 'type' => '2', 'createtime' =>time(), 'status' => '1', 'title' =>"余额抵扣", 'money' =>-$order['deductcredit2'], 'rechargetype' => 'dingdan_dikou');
                                                                pdo_insert('ewei_shop_member_log', $data);
                                                         }
                                    if($order['gift_card'] > 0){
                                                                $shopset = m('common')->getSysset('shop');
                                                                m('member')->setGift($order['openid'], 'gift_card', -$order['gift_card'], array(0, $shopset['name'] . "礼品抵扣: {$order['gift_card']} 订单号: " . $order['ordersn']));  
                                     }
                                                        $this->setStocksAndCredits($orderid, 1);
                                                        $url = "./index.php?i={$_W['uniacid']}&c=entry&m=ewei_shop&do=order&t=detail&id={$orderid}";
                                                        m('notice')->sendOrderMessage($orderid);
                                                        if (p('commission')) {
                                                                p('commission')->checkOrderPay($order['id']);
                                                        }
                                                }
                                                show_json(1, array('order' => $order, 'address' => $address, 'carrier' => $carrier));
                                        }
                                }
             }
	}
	function setStocksAndCredits($orderid = '', $type = 0)
	{
		global $_W;
		$order = pdo_fetch('select id,price,openid,dispatchtype,addressid,carrier,status from ' . tablename('ewei_shop_order') . ' where id=:id limit 1', array(':id' => $orderid));
		$goods = pdo_fetchall("select og.goodsid,og.total,g.totalcnf,g.credit,og.optionid,g.total as goodstotal,og.optionid,g.sales,g.salesreal from " . tablename('ewei_shop_order_goods') . " og " . " left join " . tablename('ewei_shop_goods') . " g on g.id=og.goodsid " . " where og.orderid=:orderid and og.uniacid=:uniacid ", array(':uniacid' => $_W['uniacid'], ':orderid' => $orderid));
		$credits = 0;
		foreach ($goods as $g) {
			$stocktype = 0;
			if ($type == 0) {
				if ($g['totalcnf'] == 0) {
					$stocktype = -1;
				}
			} else {
				if ($type == 1) {
					if ($g['totalcnf'] == 1) {
						$stocktype = -1;
					}
				} else {
					if ($type == 2) {
						if ($order['status'] >= 1) {
							if ($g['totalcnf'] == 1) {
								$stocktype = 1;
							}
						} else {
							if ($g['totalcnf'] == 0) {
								$stocktype = 1;
							}
						}
					}
				}
			}
			if (!empty($stocktype)) {
				if (!empty($g['optionid'])) {
					$option = m('goods')->getOption($g['goodsid'], $g['optionid']);
					if (!empty($option) && $option['stock'] != -1) {
						$stock = -1;
						if ($stocktype == 1) {
							$stock = $option['stock'] + $g['total'];
						} else {
							if ($stocktype == -1) {
								$stock = $option['stock'] - $g['total'];
								$stock <= 0 && ($stock = 0);
							}
						}
						if ($stock != -1) {
							pdo_update('ewei_shop_goods_option', array('stock' => $stock), array('uniacid' => $_W['uniacid'], 'goodsid' => $g['goodsid'], 'id' => $g['optionid']));
						}
					}
				}
				if (!empty($g['goodstotal']) && $g['goodstotal'] != -1) {
					$totalstock = -1;
					if ($stocktype == 1) {
						$totalstock = $g['goodstotal'] + $g['total'];
					} else {
						if ($stocktype == -1) {
							$totalstock = $g['goodstotal'] - $g['total'];
							$totalstock <= 0 && ($totalstock = 0);
						}
					}
					if ($totalstock != -1) {
						pdo_update('ewei_shop_goods', array('total' => $totalstock), array('uniacid' => $_W['uniacid'], 'id' => $g['goodsid']));
					}
				}
			}
			$credits += $g['credit'] * $g['total'];
			if ($type == 0) {
				pdo_update('ewei_shop_goods', array('sales' => $g['sales'] + $g['total']), array('uniacid' => $_W['uniacid'], 'id' => $g['goodsid']));
			} elseif ($type == 1) {
				if ($order['status'] >= 1) {
					pdo_update('ewei_shop_goods', array('salesreal' => $g['salesreal'] + $g['total']), array('uniacid' => $_W['uniacid'], 'id' => $g['goodsid']));
				}
			}
		}
		$shopset = m('common')->getSysset('shop');
		if ($type == 1) {
			m('member')->setCredit($order['openid'], 'credit1', $credits, array(0, $shopset['name'] . '购物积分 订单号: ' . $order['ordersn']));
		} elseif ($type == 2) {
			if ($order['status'] >= 1) {
				m('member')->setCredit($order['openid'], 'credit1', -$credits, array(0, $shopset['name'] . '购物取消订单扣除积分 订单号: ' . $order['ordersn']));
			}
		}
	}
        //检测订单是否24小时未付款
        function checkisclose(){
         	global $_W;
		$allgroups = pdo_fetchall("select * from" . tablename('ewei_shop_order') . "where status=0 and uniacid='{$_W['uniacid']}'");
		$now = time();
		foreach ($allgroups as $key => $value) {
			$shouldpaytime = $value['createtime']+60*60*24;
			if ($shouldpaytime < $now) {
				pdo_update('ewei_shop_order', array('status' => -1, 'canceltime' =>$now, 'cancelinfo' =>"订单24小时未付款，系统自动关闭订单"), array('ordersn' => $value['ordersn'], 'uniacid' => $_W['uniacid']));
			}
		}
        }
        //让总订单与子订单状态同步
        function update_order_status(){
           global $_W;
           $nowtime=time();
           //查询所有总订单
           $allorder=pdo_fetchall("select * from ".tablename("ewei_shop_order")." where uniacid='{$_W['uniacid']}' and TotalId=1");
           foreach($allorder as $key=>$value){
             //查询对应的子订单是否状态一致
             $zhiorder=pdo_fetchall("select * from ".tablename("ewei_shop_order")." where uniacid='{$_W['uniacid']}' and TotalId='{$value['id']}'");
             //获取子订单的个数
             $zhinum=pdo_fetchcolumn("select count(*) from ".tablename("ewei_shop_order")." where uniacid='{$_W['uniacid']}' and TotalId='{$value['id']}'");
             $num1=0;//子订单待收货状态初始值
             $num2=0;//子订单已完成状态初始值
             $num3=0;//子订单待发货退款状态初始值
             $num4=0;//子订单待发货退款状态初始值
             $num5=0;//子订单已退款状态初始值
             foreach($zhiorder as $k=>$v){
                 //子订单待收货状态
                 if($v['status']==2 && $v['refundid']==0){
                    $num1++;
                 }
                 //子订单已完成状态
                 if($v['status']==3 && $v['refundid']==0){
                     $num2++;
                 }
                 //子订单待发货退款状态
                 if($v['status']==1 && $v['refundid']!=0){
                     $num3++;
                 }
                 //子订单待收货退款状态
                 if($v['status']==2 && $v['refundid']!=0){
                     $num4++;
                 }
                 //子订单已退款状态
                 if($v['status']==-1){
                      //查询子订单是否退款
                     $zhirefund=pdo_fetch("select * from ".tablename("ewei_shop_order_refund")." where uniacid=:uniacid and orderid=:orderid and status=1 ",array(":uniacid"=>$_W['uniacid'],":orderid"=>$v['id']));
                     if(!empty($zhirefund)){
                      $num5++;   
                     }
                 }
             }
             //如果所有子订单都是待收货状态就将总订单变成待收货状态
             if($zhinum == $num1 && $num1>=2 && $value['status']!=2){
                 pdo_update("ewei_shop_order",array("status"=>2,'sendtime'=>$nowtime),array("id"=>$value['id']));
             }
             //如果所有子订单都是已完成状态就将总订单变成已完成状态
             if($zhinum == $num2 && $num2>=2 && $value['status']!=3){
                 pdo_update("ewei_shop_order",array("status"=>3,'finishtime'=>$nowtime),array("id"=>$value['id']));
             }
             //如果所有子订单都是待发货退款状态就将总订单变成待发货退款状态
             $refund=pdo_fetch("select * from ".tablename("ewei_shop_order_refund")." where uniacid=:uniacid and orderid=:orderid ",array(":uniacid"=>$_W['uniacid'],":orderid"=>$value['id']));
             if($zhinum == $num3 && $num3>=2 && empty($refund)){
                 $refundno3=m('common')->createNO('order_refund', 'refundno', 'SR');
                 $data=array(
                    "uniacid"=>$_W['uniacid'],
                     'orderid'=>$value['id'],
                     'refundno'=>$refundno3,
                     'price'=>$value['price'],
                     'reason'=> "所有子订单退款，总订单自动变成退款状态",
                     'status'=>0,
                     'createtime'=>$nowtime
                 );
                 pdo_insert("ewei_shop_order_refund",$data);
                 $refundid3=pdo_insertid();
                 pdo_update("ewei_shop_order",array("refundid"=>$refundid3,'refundtime'=>$nowtime),array("id"=>$value['id']));
             }
             if($zhinum == $num4 && $num4>=2 && $value['status']!=2){
                 pdo_update("ewei_shop_order",array("status"=>2,'sendtime'=>$nowtime),array("id"=>$value['id']));
             }
             if($zhinum == $num5 && $num5>=2 && $value['status']!=-1 ){
                 if(!empty($refund)){
                 pdo_update("ewei_shop_order_refund",array("status"=>1),array("orderid"=>$value['id']));
                 pdo_update("ewei_shop_order",array("status"=>-1,'refundid'=>""),array("id"=>$value['id']));
                 }else{
                 $refundno3=m('common')->createNO('order_refund', 'refundno', 'SR');
                 $data=array(
                    "uniacid"=>$_W['uniacid'],
                     'orderid'=>$value['id'],
                     'refundno'=>$refundno3,
                     'price'=>$value['price'],
                     'reason'=> "所有子订单退款，总订单自动变成退款状态",
                     'status'=>1,
                     'createtime'=>$nowtime
                 );
                 pdo_insert("ewei_shop_order_refund",$data);
                 pdo_update("ewei_shop_order",array("status"=>-1,'refundtime'=>$nowtime),array("id"=>$value['id']));
                 }
             }
           }
        }
}